package com.hundsun.data.uitls;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.hundsun.data.properties.DataCommonConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author pw
 * @date 2024年06月12日
 * @describe
 **/
@Component
@Slf4j
public class ExcelExportUtils {

    @Autowired
    private DataCommonConfigProperties dataCommonConfig;
    public void exportByEntity(ExportParams entity, Class<?> pojoClass, Collection<?> dataSet, String fileName) {
        Workbook workbook = ExcelExportUtil.exportExcel(entity, pojoClass, dataSet);
        export(fileName, workbook);
    }

    public void exportByMap(List<Map<String, Object>> list, ExcelType type, String fileName) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, type);
        export(fileName, workbook);

    }

    private void export(String fileName, Workbook workbook) {
        String string = dataCommonConfig.excel.getDownloadPath() + File.separator + fileName;
        File file = new File(string);
        try(FileOutputStream  fileOutputStream = new FileOutputStream(file)){
            workbook.write(fileOutputStream);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }finally {
            try {
                workbook.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
